@namespace BulmaRazor.Components
@inherits BulmaComponentBase
@inject BulmaRazorJsInterop JsInterop
<div id="@Id" @attributes="Attributes" class="@classes">
    @ChildContent
</div>

@code {

    string classes => CssBuilder.Default("is-collapsible")
        .AddClassFromAttributes(Attributes)
        .AddClass("is-active", IsActive)
        .Build();

    [Parameter]
    public string Id { get; set; }

    [Parameter]
    public bool IsActive { get; set; }

    [CascadingParameter]
    private CollapsibleContainer Parent { get; set; }

    public override async Task SetParametersAsync(ParameterView parameters)
    {
        await base.SetParametersAsync(parameters);
        if (Parent != null)
        {
            Attributes["data-parent"] = Parent.Id;
            if (Parent.AllowMultiple)
            {
                Attributes["data-allow-multiple"] = "true";
            }
        }
    }

    [Parameter]
    public RenderFragment ChildContent { get; set; }


    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);
        if (Parent == null && firstRender)
        {
            await JsInterop.CollapsibleAttach($"#{Id}");
        }
    }

    [Parameter]
    public EventCallback<Collapsible> BeforeExpand { get; set; }
    [Parameter]
    public EventCallback<Collapsible> AfterExpand { get; set; }
    [Parameter]
    public EventCallback<Collapsible> BeforeCollapse { get; set; }
    [Parameter]
    public EventCallback<Collapsible> AfterCollapse { get; set; }
    
    protected override void OnInitialized()
    {
        base.OnInitialized();
        JSCallbackManager.AddEventHandler(Id,"before:expand",new Func<Task>(()=> BeforeExpand.InvokeAsync(this)));
        JSCallbackManager.AddEventHandler(Id,"after:expand",new Func<Task>(()=> AfterExpand.InvokeAsync(this)));
        JSCallbackManager.AddEventHandler(Id,"before:collapse",new Func<Task>(()=> BeforeCollapse.InvokeAsync(this)));
        JSCallbackManager.AddEventHandler(Id,"after:collapse",new Func<Task>(()=> AfterExpand.InvokeAsync(this)));
    }

    protected override ValueTask DisposeAsync(bool disposing)
    {
        JSCallbackManager.DisposeObject(Id);
        return base.DisposeAsync(disposing);
    }

}